package com.chrishobson.jreeglut;

import static  com.chrishobson.jreeglut.glut.*;

import java.util.HashMap;

/**
 * Java wrapper to a menu in glut. 
 * 
 * @author clh
 * 
 */
public class glutMenu {

  public glutMenu() {
    m_Id = Integer.valueOf(glutCreateMenu());
    s_Map.put(m_Id, this);
  }
  
  /**
   * Sets this menu as the current glut menu
   */
  void SetMenu() {
    glutSetMenu(m_Id.intValue());
  }
  
  /**
   * Adds the entry to the menu, the object is passed to the menu handler
   * when the menu is selected, along with the window in which the menu
   * was selected.
   */
  void AddEntry(
    String a_Text
  , Object a_Key
  )
  {
    SetMenu();
    glutAddMenuEntry(a_Text, ++m_EntryId);
    
    s_EntryMap.put(Integer.valueOf(m_EntryId), a_Key);
  }
  
  void AddSubMenu(
    String a_Text
  , glutMenu a_Menu
  )
  {
    SetMenu();
    glutAddSubMenu(a_Text, a_Menu.m_Id.intValue());
  }
  
  @SuppressWarnings("unused")
  private static void Menu(
    int a_WindId
  , int a_MenuId
  , int a_Item
  )
  {
    // Menus are a bit complicated because glut passes an integer to say which
    // menu element was clicked and we also provide a mapping between a menu item
    // and an Object as that is more Java like. So bundle everything into a MenuData
    // to keep it all tidy. Then hand off to the glutWindow for dispatch to
    // its menu handler.
    MenuData l_D = new MenuData(MapMenu(a_MenuId), a_Item, s_EntryMap.get(Integer.valueOf(a_Item)));
    glutWindow.Menu(a_WindId, l_D);
  }
  
  /**
   * Maps a glut menu id to a glutMenu
   * 
   * @param a_Id
   *          The glut window id
   * @return a glutWindow
   */
  static private glutMenu MapMenu(int a_Id) {
    return s_Map.get(a_Id);
  }
  
  private Integer m_Id;
  private static int m_EntryId;
  
  static private HashMap<Integer, glutMenu> s_Map = new HashMap<Integer, glutMenu>();
  static private HashMap<Integer, Object> s_EntryMap = new HashMap<Integer, Object>();
}
